/**  
* Copyright (c) 2009, Noel Lynch All rights reserved. Redistribution and use  
* in source and binary forms, with or without modification, are permitted  
* provided that the following conditions are met: Redistributions of source  
* code must retain the above copyright notice, this list of conditions and the  
* following disclaimer. Redistributions in binary form must reproduce the above  
* copyright notice, this list of conditions and the following disclaimer in the  
* documentation and/or other materials provided with the distribution. Neither  
* the name of Noel Lynch nor the names of contributors may be used to  
* endorse or promote products derived from this software without specific prior  
* written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT  
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A  
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR  
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,  
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;  
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,  
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR  
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF  
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
*/
// created by noellynch
// Oct 8, 2009

package com.sceneworker.editors.textureeditorlister;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.util.concurrent.Callable;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import net.miginfocom.swing.MigLayout;

import com.jme.image.Texture;
import com.jme.math.Vector2f;
import com.jme.scene.Spatial;
import com.jme.util.GameTaskQueueManager;
import com.jme2utils.objects.TextureReferenceArray;
import com.jme2utils.staticutils.TextureUtils;
import com.myjavautils.swing.MigLayoutUtils;
import com.myjavautils.swing.SwingComponentFactory;
import com.sceneworker.app.events.DelegateEventTypes;
import com.sceneworker.app.globals.SceneWorkerGlobals;
import com.sceneworker.app.globals.cacheobjects.TexturePainterCacheObject;
import com.sceneworker.editors.texturepainter.TexturePainterPanel;
import com.sceneworker.editors.texturepainter.brushgenerator.BrushImage;
import com.sceneworker.util.delegation.DelegationEvent;
import com.sceneworker.util.delegation.DelegationEventBroadcaster;
import com.sceneworker.util.delegation.DelegationEventListener;
import com.sceneworker.util.swing.imagelist.SimpleImageList;

public class TextureListerPanel extends JPanel implements DelegationEventListener{

	private		TextureReferenceArray		mcl_textureRef;
	private		SimpleImageList				mcl_imageList;
	private		JScrollPane					mcl_scroller;
	private		TexturePainterPanel			mcl_texturePainterPanel;
	
	public	TextureListerPanel(final JDialog cl_dlg) {
		mcl_textureRef = new TextureReferenceArray();
		
		setLayout(new MigLayout("inset 5"));
		
		mcl_imageList = new SimpleImageList();
		mcl_imageList.setImageSelectionListener(new SimpleImageList.IImageSelectionListener() {
			public void imageSelected(SimpleImageList cl_list) {
				handleNewTextureSelection();
			}
		});
		
		mcl_scroller = new JScrollPane();
		mcl_scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		mcl_scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		mcl_scroller.setViewportView(mcl_imageList);
		mcl_scroller.setMinimumSize(mcl_imageList.getMinimumSize());
		//add(mcl_scroller, "width " + (SimpleImageList.IMAGE_WIDTH + 30) + ", height 100%");
		add(mcl_scroller, "width 30%, height 100%");
		
		mcl_texturePainterPanel = new TexturePainterPanel(null);
		add(mcl_texturePainterPanel, "width 70%, height 100%, wrap");
		
		final	TextureListerPanel		lcl_this = this;
		
		JButton		lcl_closeBtn = SwingComponentFactory.makeAButton("Close");
		lcl_closeBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DelegationEventBroadcaster.inst().removeEventListener(lcl_this);
				SceneWorkerGlobals.inst().removeFromCache(TexturePainterCacheObject.TEXTURE_PAINTER);
				cl_dlg.dispose();
			}
		});
		
		cl_dlg.addWindowListener(new WindowListener() {

			public void windowActivated(WindowEvent e) {
			}

			public void windowClosed(WindowEvent e) {
			}

			public void windowClosing(WindowEvent e) {
				DelegationEventBroadcaster.inst().removeEventListener(lcl_this);
				SceneWorkerGlobals.inst().removeFromCache(TexturePainterCacheObject.TEXTURE_PAINTER);
			}

			public void windowDeactivated(WindowEvent e) {
			}

			public void windowDeiconified(WindowEvent e) {
			}

			public void windowIconified(WindowEvent e) {
			}

			public void windowOpened(WindowEvent e) {
			}
			
		});
		
		MigLayoutUtils.makeRightAlignedButtonBar(this, lcl_closeBtn);
		
		DelegationEventBroadcaster.inst().addEventListener(DelegateEventTypes.NEW_SPATIAL_SELECTION_EVT, this);
	}

	public void handleEvent(DelegationEvent cl_e) {
		if(cl_e.getEventType().equals(DelegateEventTypes.NEW_SPATIAL_SELECTION_EVT)) {
			Spatial		lcl_s = (Spatial)cl_e.getObjectData()[0];
			updateTextureList(lcl_s);
		}
	}
	
	public	void	updateTextureList(Spatial cl_newSel) {
		mcl_textureRef.clear();
		
		if(cl_newSel != null) {
			System.out.println("new spatial selected " + cl_newSel.getName());
			TextureUtils.findAllTextures(cl_newSel, mcl_textureRef);
			
			for(Texture lcl_t : mcl_textureRef.getTextureArray()) {
				System.out.println(lcl_t.getTextureId());
			}
		}
		
		GameTaskQueueManager.getManager().update(new Callable<Void>() {
			public Void call() throws Exception {
				initImageList();
				repaint();
				return null;
			}
		});
	}
	
	public	void	paintAt(Vector2f cl_uv) {
		if(mcl_imageList.getCurrentImageSelectionIndex() == -1) {
			return;
			//SimpleAlert.doAlert("You have not selected a texture to paint in.", this);
		}
		mcl_texturePainterPanel.paintFromUV(cl_uv);
	}
	
	private	void	initImageList() {
		for(Texture lcl_t : mcl_textureRef.getTextureArray()) {
			if(lcl_t.getImage() != null) {
				final	BufferedImage		lcl_im = TextureUtils.createBufferedImageFromTexture(lcl_t, null, true);
				mcl_imageList.addDrawImage(new SimpleImageList.IDrawImage() {
					public Image getImage() {
						return lcl_im;
					}
				});			
			}
		}
		
		mcl_imageList.revalidate();
		mcl_scroller.revalidate();
		mcl_scroller.repaint();
	}
	
	public	BrushImage		getBrush() {
		return mcl_texturePainterPanel.getBrush();
	}
	
	private	void	handleNewTextureSelection() {
		int		li_curSel = mcl_imageList.getCurrentImageSelectionIndex();
		System.out.println("sel = " + li_curSel);
		Texture		lcl_texture = mcl_textureRef.getTextureAt(li_curSel);
		mcl_texturePainterPanel.updateWithNewTexture(lcl_texture);
		mcl_texturePainterPanel.repaint();
	}
	
}
